package jeconbond.economic.resources;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ResourceStorrage {
	private Map<IResourceType, ResourceBasket> map = new HashMap<IResourceType, ResourceBasket>();
	private double eps = 1e-7;
	
	public ResourceStorrage(double eps) {
		this.eps = eps;
	}
	
	public ResourceStorrage(Map<IResourceType, ResourceBasket> map) {
		this.map = map;
	}

	public ResourceStorrage() {}
	
	private ResourceBasket get(IResourceType type) {
		ResourceBasket rb = map.get(type);
		if (rb == null) {
			map.put(type, new ResourceBasket(type));
		}
		return map.get(type);
	}
	
	public double howMuchWasStored(IResourceType type) {
		return get(type).value;
	}

	public void storeResource(IResourceType type, double value) {
		get(type).value += value;
	}

	public double receiveResource(IResourceType type, double value) {
		ResourceBasket rb = get(type);
		value = Math.min(rb.value, value);
		rb.value -= value;
		if (Math.abs(rb.value) < eps) {
			rb.value = 0.0;
		}
		return value;
	}

	public Collection<ResourceBasket> listBaskets() {
		return map.values();
	}

	public void storeResource(ResourceBasket rb) {
		storeResource(rb.type, rb.value);
	}
	
	public String toString() {
		List<ResourceBasket> rbs = new ArrayList<ResourceBasket>(map.values());
		Collections.sort(
				rbs, 
				new Comparator<ResourceBasket>() {
					@Override
					public int compare(ResourceBasket a, ResourceBasket b) {
						return a.type.getName().compareTo(b.type.getName());
					}
				}
		);
		StringBuilder sb = new StringBuilder();
		for (ResourceBasket rb : rbs) {
			sb.append(rb).append(", ");
		}
		return sb.toString();
	}

	public void clear() {
		for (ResourceBasket rb : map.values()) {
			rb.value = 0.0;
		}
	}
}
